package social;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CreateMailServlet
 */
@WebServlet("/CreateMailServlet")
public class CreateMailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateMailServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String messageBody = request.getParameter("messageBody");
		String toUser = request.getParameter("toUser");
		//System.out.println("toUser = " + toUser);
		//System.out.println("messageBody = " + messageBody);
		SocialDBC db = (SocialDBC) getServletContext().getAttribute("database");
		if (db.userExists(toUser)) {
			HttpSession session = request.getSession();
			db.addMail(toUser, (String) session.getAttribute("username"), messageBody, "note");
			response.sendRedirect("mailbox.jsp");
//			request.getRequestDispatcher("mailbox.jsp").forward(request, response);
		} else {
			request.setAttribute("userExist", toUser);
			request.getRequestDispatcher("create-mail.jsp").forward(request, response);
		}
	}

}
